<?php

/**
 * User: 刘红伟
 * Email: 454303753@qq.com
 * File:wechatcallbackapi.php
 */
class wechatcallbackapi {
    protected  $echostr;
    protected $signature;
    protected $timestamp;
    protected $nonce;

    protected $_POST_DATA;
    protected $_POST;

    private $toUserName;	// 开发者微信号
    private $fromUserName;	// 发送方帐号（一个OpenID）

      private  $token;
    public function __construct($nonce,$timestamp,$signature,$echostr){
        $this->echostr=$echostr;
        $this->signature=$signature;
        $this->timestamp=$timestamp;
        $this->nonce =$nonce;
        $this->_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");

    }
    public function valid($token){
        $this->token=$token;
        if($this->checkSignature()){
          //  echo $this->checkSignature();exit;
            libxml_disable_entity_loader(TRUE);
            $this->_POST = simplexml_load_string($this->_POST_DATA, 'SimpleXMLElement', LIBXML_NOCDATA);
            if($this->_POST){
            $this->toUserName 	= strval($this->_POST->ToUserName);
            $this->fromUserName	= strval($this->_POST->FromUserName);
            $this->msgType		= $this->_POST->MsgType;
            }
        switch($this->msgType){
            case 'event':
                $this->_parseEvent();
                break;
        }

        }else{
            echo '';exit;
        }


    }


    public function get($field){
        $arr = (array)$this->_POST;

        if (isset($arr[$field]))
        {
            $result = $arr[$field];
        }
        return $result;
    }

    public function _parseEvent(){
        $this->event = $this->get('Event');
        if($this->event){
            $this->responseMsg($this->event);
        }

    }




    public function responseMsg($method='')
    {
        switch($method){
            case 'subscribe':
                $this->_subscribe();
                break;
            case 'SCAN':
                $this->_scan();
                break;
            case 'CLICK':
                $this->_click();
                break;
            case 'VIEW':
                $this->_view();
                break;


        }
    }

    /**
     * 用户直接关注的消息
     *
     */

    public function _text(){
        $fromUsername = $this->fromUserName;
        $toUsername = $this->toUserName;
        $time = time();
        $tpl= new wechattemplate('text');
        $textTpl=$tpl->getTpl();
        $contentStr = "欢迎关注漫行旅游租车，在这里您可以与我们分享您的骑行感受，或对我们的服务提出宝贵意见和建议，谢谢！";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,  $contentStr);
        echo $resultStr;
    }
    private function setText($contentStr){
        $fromUsername = $this->fromUserName;
        $toUsername = $this->toUserName;
        $time = time();
        $tpl= new wechattemplate('text');
        $textTpl=$tpl->getTpl();
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,  $contentStr);
        echo $resultStr;
    }
    private function _view(){
        $this->_text();
    }
    private function _click(){
        $fromUsername = $this->fromUserName;
        $toUsername = $this->toUserName;
        $time = time();
        $tpl= new wechattemplate('text');
        $textTpl=$tpl->getTpl();
        $contentStr = "客服电话：40000000000000";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,  $contentStr);
        echo $resultStr;
    }

    private  function _scan(){

        $fromUsername = $this->fromUserName;
        $EventKey=$this->get('EventKey');

        if($EventKey){



        $inform_config= $this->msg_config($fromUsername,$EventKey);
        switch($inform_config['status']){
            case 20:
             $temapi=  new wechattemplateapi($this->token,$inform_config['inform_config'],3);
             $temapi->send();//通知不成功，未做记录
            break;
            case 21:
                $this->setText('非法数据，请勿相信！');
                break;
            case 22:
                $this->setText('此车不在锁柱，请借其它辆！');
                break;
            case 30:
                $this->setText('锁具密码：'.$inform_config['bike_pass'].'，前方美景在等您！');
                break;
            case 31:
                $this->setText('这不是您的自行车，别骑错哦！');
                break;

            case 40:
                $this->setText('此车暂不能租借，请扫描充电桩上的自行车');
                break;
            case 60:
                $this->setText('锁柱已坏，请扫描其他充电桩');
                break;
            case 61:
                $this->setText('无锁柱，请扫描其他充电桩');
                break;
            case 62:
                $this->setText('此锁柱无自行车，请借其它辆！');
                break;
            case 99:
                $this->setText('这辆车可能坏了吧，扫描其他车辆二维码试试吧！');
                break;
            case 100:
                $this->setText('网络通信出现错误，请扫描其他充电桩');
                break;
            case 101:
                $this->setText('硬件未响应，请扫描其他充电桩');
                break;
            case 102:
                $this->setText('您所借的车锁已解锁，请取车');
                break;
            case 103:
                $this->setText('通信有异常，无法取车！请等待几分钟再试或联系客服！');
                break;
            default :
                $this->setText('这辆车可能坏了吧，扫描其他车辆二维码试试吧！');
        }

        }else{
            $this->_text();
        }
    }
    private function _subscribe(){
        $fromUsername = $this->fromUserName;
        $toUsername = $this->toUserName;
        $EventKey=$this->get('EventKey');
        $time = time();
         if($EventKey){
             $EventKey=$this->get('EventKey');
             $key_arr=explode('_',$EventKey);
             if(isset($key_arr[2])){
                 $EventKey=$key_arr[1].'_'.$key_arr[2];
             }else{
                 $EventKey=$key_arr[1];
             }

             $inform_config= $this->msg_config($fromUsername,$EventKey);
             switch($inform_config['status']){
                 case 20:
                     $temapi=  new wechattemplateapi($this->token,$inform_config['inform_config'],3);
                     $temapi->send();//通知不成功，未做记录
                     break;
                 case 21:
                     $this->setText('非法数据，请勿相信！');
                     break;
                 case 22:
                     $this->setText('此车不在锁柱，请借其它辆！');
                     break;
                 case 30:
                     $this->setText('锁具密码：'.$inform_config['bike_pass'].'，前方美景在等您！');
                     break;
                 case 31:
                     $this->setText('此车不属于你，请借其它辆或找回自己的车！');
                     break;

                 case 40:
                     $this->setText('此车暂不能租借，请扫描充电桩上的自行车');
                     break;
                 case 60:
                     $this->setText('锁柱已坏，请扫描其他充电桩');
                     break;
                 case 61:
                     $this->setText('无锁柱，请扫描其他充电桩');
                     break;
                 case 62:
                     $this->setText('此锁柱无自行车，请借其它辆！');
                     break;
                 case 99:
                     $this->setText('这辆车可能坏了吧，扫描其他车辆二维码试试吧！');
                     break;
                 case 100:
                     $this->setText('网络通信出现错误，请扫描其他充电桩');
                     break;
                 case 101:
                     $this->setText('硬件未响应，请扫描其他充电桩');
                     break;
                 case 102:
                     $this->setText('您所借的车锁已解锁，请取车');
                     break;
                 case 103:
                     $this->setText('通信有异常，无法取车！请等待几分钟再试或联系客服！');
                     break;
                 default :
                     $this->setText('这辆车可能坏了吧，扫描其他车辆二维码试试吧！');
             }
         }else{
             $tpl= new wechattemplate('text');
             $textTpl=$tpl->getTpl();
             $contentStr = '欢迎关注漫行旅游租车，在这里您可以与我们分享您的骑行感受。免注册直接<a href="'.Yii::app()->params['weixin_realm'].Yii::app()->createUrl('home/index').'">登陆</a>';
             $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,  $contentStr);
             echo $resultStr;
         }

    }


    /*
	 * 文本消息
	 *
	 * ToUserName: 		开发者微信号
	 * FromUserName:	发送方帐号（一个OpenID）
	 * CreateTime:		消息创建时间 （整型）
	 * MsgType:			text
	 * Content:			文本消息内容
	 * MsgId:			消息id，64位整型
	 */





    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $this->signature;
        $timestamp = $this->timestamp;
        $nonce = $this->nonce;

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

  private  function  msg_config($fromUsername,$EventKey){


      /**
       * 现在只有自行车编号
       */
      $data=array();
      $bike_name='未知自行车';
      $location_name='未知网点';
      $bike_no='';
      $is_bike=1;
      $bike_mac_no='';//自行车的物理遍号
      $controller_no='';
      $status=0;
      if($EventKey){
          $type =explode('_',$EventKey);
          /*
         * 扫描锁柱遍号
         * 查看服务器数据库的锁柱与自行车的关系
         *    在锁与车池中：直接返回自行车的遍号
         *    不在锁与车的池中：调用接口查看实际硬件是否锁与车在通信 是：返回自行车遍号。否：返回状态码
         *
         * **/
          if(isset($type[1]))
          {
                if($type[0] == 'L')
                {
                    $is_bike        =   0;
                    //查锁柱
                   $lock_no         =   $type[1];
                    //查看锁柱是否存在。并查看锁柱状态
                    $l_lock_data    =  Yii::app()->db->createCommand()->from('lock_cylinder')->where('lock_cylinder_no=:lock_cylinder_no',array(':lock_cylinder_no'=>$lock_no))->queryRow();
                    //存在
                    if($l_lock_data)
                    {
                        $lock_id        =   $l_lock_data['lock_cylinder_id'];
                        $lock_mac_no    =   $l_lock_data['lock_mac_no'];
                        //锁柱已坏时
                        if($l_lock_data['status'] == 1)
                        {
                            $data                   =   array();
                            $data['status']         =   60;
                            $data['inform_config']  =   array();
                            return $data;
                        }
                    }else
                    {
                        //不存在
                        $data                   =   array();
                        $data['status']         =   61;
                        $data['inform_config']  =   array();
                        return $data;
                    }
                    //锁柱存在时，查看锁上可有车
                   $l_bike_lock_data= Yii::app()->db->createCommand()->from('bike_lock_relation')->where('lock_cylinder_id=:lock_cylinder_id',array(':lock_cylinder_id'=>$lock_id))->queryRow();
                    if($l_bike_lock_data)
                    {
                        //存在时
                        $l_bike_data= Yii::app()->db->createCommand()->select('bike_id,bike_mac_no,bike_no,bike_category_id,status')->from('bike')->where('bike_id=:bike_id',array(':bike_id'=>$l_bike_lock_data['bike_id']))->queryRow();
                        if(!$l_bike_data){
                            $data                   =   array();
                            $data['status']         =   62;
                            $data['inform_config']  =   array();
                            return $data;
                        }
                        $bike_no    =   $l_bike_data['bike_no'];

                    }
                    else
                    {

                        $data                   =   array();
                        $data['status']         =   100;
                        $data['inform_config']  =   array();
                        return $data;
                    }


                }else
                {
                    $bike_no=$type[1];
                }
          }else
          {
              $bike_no=$type[0];
          }
      }


      $bike_data= Yii::app()->db->createCommand()->select('bike_id,bike_no,bike_password,bike_mac_no,bike_category_id,status')->from('bike')->where('bike_no=:bike_no',array(':bike_no'=>$bike_no))->queryRow();
      if($bike_data)
      {


             //根据
              $_bike_json       =   $this->getData(Yii::app()->params['hardware_api_url'].'bike?bikecode='.$bike_data['bike_mac_no']);
              $_bike_result     =   json_decode($_bike_json,1);

              if($_bike_result)
              {
                  if(isset($_bike_result['errcode']) && $_bike_result['errcode']>0)
                  {
                      $data                     =   array();
                      $data['status']           =   100;
                      $data['inform_config']    =   array();
                      return $data;
                  }

                  //网络是否通
                  if(isset($_bike_result['code']) && !empty($_bike_result['code']))
                  {
                      $_state_json=  $this->getData(Yii::app()->params['hardware_api_url'].'query_state?code='.$_bike_result['code']);
                      $_state_result=json_decode($_state_json,1);
                      if($_state_result)
                      {
                          if(isset($_state_result['errcode']) && $_state_result['errcode']>0)
                          {
                              $data                     =   array();
                              $data['status']           =   100;
                              $data['inform_config']    =   array();
                              return $data;
                          }


                          if(isset($_state_result['stations']['online'])&&!$_state_result['stations']['online'])
                          {
                              $data                     =   array();
                              $data['status']           =   100;
                              $data['inform_config']    =   array();
                              return $data;
                          }
                          if(isset($w_data['stations']['status']) && $w_data['stations']['status']!=1)
                          {
                              $data                     =   array();
                              $data['status']           =   100;
                              $data['inform_config']    =   array();
                              return $data;
                          }
                          if(isset($w_data['stations']['devicestatus']) && ($w_data['stations']['devicestatus']==0 || $w_data['stations']['devicestatus'] & 1 == 0 || $w_data['stations']['devicestatus'] & 2 == 0))
                          {
                              $data                     =   array();
                              $data['status']           =   100;
                              $data['inform_config']    =   array();
                              return $data;
                          }

                      }else
                      {
                          $data                     =   array();
                          $data['status']           =   100;
                          $data['inform_config']    =   array();
                          return $data;
                      }

                  }

              }else
              {
                  $data                     =   array();
                  $data['status']           =   100;
                  $data['inform_config']    =   array();
                  return $data;
              }
              /**
               * 车与人的情况
               * 人的余额
               */
              $auth_data    =    Yii::app()->db->createCommand()->select('auth_id,auth_uid')->from('user_auth')->where('auth_uid=:auth_uid',array(':auth_uid'=>$fromUsername))->queryRow();
              if($auth_data)
              {
                  $user_auth_data   =   Yii::app()->db->createCommand()->from('user_auth_relation')->where('auth_id=:auth_id',array(':auth_id'=>$auth_data['auth_id']))->queryRow();
                  if($user_auth_data)
                  {
                      $bike_unlock_data =   Yii::app()->db->createCommand()->from('bike_unlocking_status')->where('user_id=:user_id and bike_id=:bike_id',array(':user_id'=>$user_auth_data['user_id'],':bike_id'=>$bike_data['bike_id']))->queryAll();

                      if($bike_unlock_data){
                         foreach($bike_unlock_data as $v)
                         {
                            if($v['status']==0)
                            {

                                $_bike_unlock_data   =   Yii::app()->db->createCommand()->from('bike_unlock_relation')->where('bike_id=:bike_id and user_id=:user_id and lock_mac_no=:lock_mac_no and controller_no=:controller_no and create_time >:create_time',array(':bike_id'=>$bike_data['bike_id'],':user_id'=>$user_auth_data['user_id'],':lock_mac_no'=>$_bike_result['dockno'],':controller_no'=>$_bike_result['code'],':create_time'=>time()-120))->queryRow();
                                if($_bike_unlock_data)
                                {
                                    $data=array();
                                    $data['status']             =   102;
                                    $data['inform_config']      =   array();
                                    return $data;
                                }else
                                {
                                    $data=array();
                                    $data['status']             =   103;
                                    $data['inform_config']      =   array();
                                    return $data;
                                }

                            }

                             if($v['status']==1)
                             {
                                 $data=array();
                                 $data['status']            =   30;
                                 $data['inform_config']     =   array();
                                 $data['bike_pass']         =   $bike_data['bike_password'];
                                 return $data;
                             }
                         }

                          //查看车子是否被借走

                          if(isset($_bike_result['isout']) && $_bike_result['isout'])
                          {
                              $data                  =   array();
                              $data['status']        =   31;
                              $data['inform_config'] =   array();
                              return $data;
                          }


                      }
                  }
              }

          //获取自行车的信息
          $bike_category_data   =   Yii::app()->db->createCommand()->select('category_name')->from('bike_category')->where('category_id=:category_id',array(':category_id'=>$bike_data['bike_category_id']))->queryRow();
          if(!$bike_category_data)
          {
              $data                  =   array();
              $data['status']        =   21;
              $data['inform_config'] =   array();
              return $data;
          }
          $bike_name       =   $bike_category_data['category_name'];

          if($bike_data['status']==20)
          {
              //取出锁柱ID

              $bike_lock_data   =  Yii::app()->db->createCommand()->from('bike_lock_relation')->where('bike_id=:bike_id',array(':bike_id'=>$bike_data['bike_id']))->queryRow();
              if($bike_lock_data)
              {
                  //取网点id
                  $lock_data    =   Yii::app()->db->createCommand()->select('lock_cylinder_id,lock_cylinder_no,location_id')->from('lock_cylinder')->where('lock_cylinder_id=:lock_cylinder_id',array(':lock_cylinder_id'=>$bike_lock_data['lock_cylinder_id']))->queryRow();
              }
              if(!empty($lock_data))
              {

                  $location_data        =   Yii::app()->db->createCommand()->select('location_id,location_no,location_name')->from('location')->where('location_id=:location_id',array(':location_id'=>$lock_data['location_id']))->queryRow();
                  if($location_data)
                  {
                      $location_name    =   $location_data['location_name'];
                  }
                  $url      =   Yii::app()->params['weixin_realm'].Yii::app()->createUrl('lend/index',array('openId'=>$fromUsername,'eventkey'=>$bike_no,'expires_time'=>time()));

                  $account  =   $location_name;
                  $data     =   array();
                  $data['status']       =   20;
                  $data['inform_config']=array(
                      'url'         =>  $url,
                      'openId'      =>  $fromUsername,
                      'first'       =>  "恭喜您扫描成功",
                      'location'    =>  "{$location_name}",
                      'bike_name'   =>  "{$bike_name}",
                      'remark'      =>  "请在5分钟内完成租车，否则此链接将失效",
                      'bike_pass'   =>  "{$bike_data['bike_password']}"
                  );

                  return $data;
              }else
              {
                  $data                     =   array();
                  $data['status']           =   99;//锁与车关系表
                  $data['inform_config']    =   array();
                  return $data;
              }


          }
          elseif($bike_data['status']==30)
          {

                  $location_no          =   $_bike_result['code'];
                  $b_controller_data    =   Yii::app()->db->createCommand()->select('location_controller_id,location_controller_no,location_id,manager_id')->from('location_controller')->where('location_controller_no=:location_controller_no',array(':location_controller_no'=>$location_no))->queryRow();
                  if($b_controller_data)
                  {
                      $b_location_data  =   Yii::app()->db->createCommand()->select('location_id,location_no,location_name')->from('location')->where('location_id=:location_id',array(':location_id'=>$b_controller_data['location_id']))->queryRow();

                      if(!empty($b_location_data))
                      {
                          $location_name    =   $b_location_data['location_name'];
                          $url              =   Yii::app()->params['weixin_realm'].Yii::app()->createUrl('lend/index',array('openId'=>$fromUsername,'eventkey'=>$bike_no,'expires_time'=>time()));

                          $account          =   $location_name;
                          $data             =   array();
                          $data['status']   =   20;
                          $data['inform_config']=array(
                              'url'         =>  $url,
                              'openId'      =>  $fromUsername,
                              'first'       =>  "恭喜您扫描成功",
                              'location'    =>  "{$location_name}",
                              'bike_name'   =>  "{$bike_name}",
                              'remark'      =>  "请在5分钟内完成租车，否则此链接将失效",
                              'bike_pass'   =>  $bike_data['bike_password']
                          );
                          return $data;
                      }
                  }else
                  {
                      $data                     =   array();
                      $data['status']           =   99;
                      $data['inform_config']    =   array();
                      return $data;
                  }

          }else
          {
              $data                     =   array();
              $data['status']           =   40;
              $data['inform_config']    =   array();
              return $data;

          }

      }else
      {
          $data                     =   array();
          $data['status']           =   21;
          $data['inform_config']    =   array();
          return $data;
      }
  }
private function getData($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}


}